<?php
    
	function operation_log($operation,$type){
		$data['user_id']=$_SESSION['user']['id'];
		$data['time']=time();
		$data['operation']=$operation;
		$data['type']=$type;
		$log=M('log');
		$res=$log->add($data);
		if($res){
			return true;
		}else{
			return false;
		}
	}
	
	
	/**  添加日志
	 * $user_id；用户id
	 * $type：日志类型（请求日志，返回日志，处理日志）
	 * $operation：具体操作 如订单查询、余额查询等
	 * $data：数据
	 * $operation_time：操作时间  年-月-日 时:分:秒 格式
	 * $desc：描述
	 */
	function add_log($user_id,$type,$operation,$data,$operation_time,$desc){
		 $log=M('log');
		 
		 if(is_array($data)){
			  foreach($data as $k=>$v){
				 $str.=$k.'=>'.$v.',';
			 }
			 $str=trim($str,',');
		 }else{
			 $str=$data;
		 }
		 $arr['user_id']=$user_id;
		 $arr['type']=$type;
		 $arr['operation']=$operation;
		 $arr['data']=$str;
		 $arr['operation_time']=$operation_time;
		 $arr['desc']=$desc;
		 $res=$log->add($arr);
	}
	
	function  temp_sub($x,$y)
	{
		$z=$x-$y;
		echo $z;
	}
	
	function  temp_add($x,$y)
	{
		$z=$x+$y;
		echo $z;
	}
	
	
	function cdump($str){
		@header("Content-Type:text/html;charset=utf-8");
		echo "<pre>";
		print_r($str);
		echo "</pre>";
	}
	/**
	 * 通过字符串获取交易状态
	 */
	function tb_status($string){
		if(is_string($string)){
			switch($string){
				case "TRADE_NO_CREATE_PAY":
					$res_str = "没有创建支付宝交易";
					break;
				case "TRADE_NO_CREATE_PAY":
					$res_str = "没有创建支付宝交易";
					break;
				case "WAIT_BUYER_PAY":
					$res_str = "买家已付款,等待卖家发货";
						
					break;
				case "WAIT_BUYER_CONFIRM_GOODS":
					$res_str = "等待买家确认收货";
					break;
				case "TRADE_BUYER_SIGNED":
					$res_str = "买家已签收";
					break;
				case "TRADE_FINISHED":
					$res_str = "交易成功"; 
					break;
				case "TRADE_CLOSED": 
					$res_str = "付款以后用户退款成功，交易自动关闭";
					break;
				case "TRADE_CLOSED_BY_TAOBAO":
					$res_str = "付款以前，卖家或买家主动关闭交易";
					break;
				case "PAY_PENDING":
					$res_str = "际信用卡支付付款确认中";
					break;					
			}
		}else{
			$res_str = false;
		}
		return $res_str;
		
	}
	/**
	 * http请求（支持GET和POST）
	 * @param  [type] $url  [请求地址]
	 * @param  [type] $data [发送数据]
	 * @return [type]       [获取到的数据]
	 */
	function https_request($url, $data = null) {
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_URL, $url);
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
		
		if(!empty($data)) {
			curl_setopt($curl, CURLOPT_POST, 1);
			curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
		}
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
		$output = curl_exec($curl);
		curl_close($curl);
		return $output;
	}
	
   	/* curl post 提交      */
	function curl_post($url, $data) {
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
		$res = curl_exec($ch);
		curl_close($ch);
		return $res;
	}
	//流量单位转换
	function get_peta($inter=1){
		$num = $inter * 1;
		if($num >= 1024){
			$res = ($num / 1024)."GB";
		}else{
			 $res = $num."MB";
		}
		return $res;
	}
	
	
	/**
	 * 充值对账信息入库
	 * @param  [type] $parame [description]
	 * @return [type]         [description]
	 */
	function api_recharge($parame){
		if(empty($parame['userid'])){
			return false;
		}
		if(empty($parame['tid'])){
			return false;
		}		
		$data['Userid']  = $parame['userid'];
		$data['Password']= $parame['pwd'];
		$data['Status']  = $parame['status'];
		$data['Moblie']  = $parame['moblie'];
		$data['Sum']     = $parame['sum'];
		$data['Tid']     = $parame['tid'];
		$data['Balance'] = $parame['balance'];
		$data['Reason']  = $parame['reason'];
		$data['Remarks'] = $parame['remarks'];
	
		$data['Action'] = "Recking";
		$data['Reck_time']= date("Y-m-d H:i:s",time());
		$data['Times']  = time();
		$data['Sign']    = md5("Userid={$data['Userid']}Password={$data['Password']}Action={$data['Action']}Tid={$data['Tid']}{$data['Times']}");
		$send_url       = "http://www.kailuo.org/API/Recking.php";//接口地址
		$result         = curl_post($send_url,$data);
		return $result;
	}
	
	/**
	 * 当前获取用户信息
	 */
	function use_msg($show_pwd = false){
		$model = M("user_authorize");
		
		$field = "add_time,return_id,password,visitor_nick,visitor_id,top_session,top_appkey,id";
		if(true == $show_pwd){
			$field .= ",password_original";
		}
		$where = "visitor_id =".session("visitor_id");
		$info = $model->field($field)->where($where)->find();
		return $info;   
	
	}
	
    /**
     *  获取当前用户余额信息
     */
     function get_usless(){
        $usinfo = use_msg();
        //发送数据
        $test = array(
            "Userid"    => $usinfo['visitor_id'],
            "Password"  => $usinfo['password'],
            "Times"     => time(),
            "Action"    => "Usemsg"            
        );
		
        $test["Sign"] = md5("Userid={$test['Userid']}Password={$test['Password']}Action=Usemsg{$test['Times']}");
        $test_url = "http://www.kailuo.org/API/related.php";//请求地址
        $info = curl_post($test_url,$test);
        $info = json_decode($info,true);
        //获取到数据就返回、否则返回false
        if($info['status'] == 200){
            return $info['result_data'];
        }else{
            return false;
        }        
     }
	//根据产品编号获取产品价格
	function product_price($code,$show_face=false){
		$model = M("product");		
		//是否获取面额
		$field = $show_face == true ? "supprice,sale_face":"supprice";
		$where = "flow = '{$code}'";
		$info = $model->field($field)->where($where)->find();
		if($info){
			$result =  $show_face == true ? $info : $info['supprice'];
			return $result;
		}else{
			return '';
		}
	}
	/**
	 *	根据订单号获取 实付金额
	 */
	function order_payment($tid,$field=""){
		$model = M("orders");	
		$where["tid"] = $tid;
		$fields = empty($field)?"payment":$field;		
		$info = $model->field($fields)->where($where)->find();				
		if($info){
			return empty($info[$fields])? 0 : $info[$fields];
		}else{
			return 0;
		}
	}
	/**
	 *	扣费/充值接口
	 */
	 function PayMent($parame,$type="pay"){
		 /* 支付、扣费 */
		if($type == "pay" ){
			$send["Action"] = "Usepay";
		//充值、退款
		}elseif($type == "refund"){
			$send["Action"] = "Userefund";
		}
		$send['Userid']	= $parame['userid'];//用户id
		$send['Password']= $parame['pwd'];//密码
		$send['Times']	 = time();		//时间戳
		$send['Tid']	 = $parame['sum'];//订单号
		$send['payment'] = $parame['sum'];//金额
        $send["Sign"] = md5("Userid={$send['Userid']}Password={$send['Password']}Action={$send['Action']}{$send['Times']}");
		$send_url = "http://www.kailuo.org/API/related.php";
		
		$info = curl_post($send_url,$send);
        $info = json_decode($info,true);
		return $info;		
	 }
	 

    /**	 生成sql语句
     *	$string String 上一个条件
     *	$field 	String 字段名
     *	$value 			值
     *	$logic			逻辑 【and or 】
     *	$code 			= > < 
     *	$is_str	boolen	是否字符串
     */
    function build_where($string,$field="",$value,$logic="and",$code="=",$is_str=true){
        $result = "";
        if(empty($value)){
            return '';
        }else{
            if($string){
                $result .= " {$logic} ";
            }
            //自动是否存在
            if($field){
                //是否字符串
                if(true == $is_str){
                    $result .= "( ".$field." {$code} '".$value."' )";
                }else{
                    $result .= "( ".$field." {$code} ".$value." )";
                }
            }
            return $result;
        }
    }
	function taobao_address($sessionKey){
		$appkey = '23416550';
		$secret = 'ebbc68fc906b6436f76b4f9cda829976';
		$c = new \TopClient;
		$c->appkey = $appkey;
		$c->secretKey = $secret;
		$req = new \LogisticsAddressSearchRequest;
		$req->setRdef("get_def");
		$resp = $c->execute($req, $sessionKey);
		return( (string)$resp -> addresses -> address_result -> mobile_phone);
		die;
	}
	function send($sessionKey,$phone){
		$appkey = '23416550';
		$secret = 'ebbc68fc906b6436f76b4f9cda829976';
		$c = new \TopClient;
		$c->appkey = $appkey;
		$c->secretKey = $secret;
		$req = new \AlibabaAliqinTaSmsNumSendRequest;
		//$req->setExtend("123456");
		$req->setSmsType("normal");
		$req->setSmsFreeSignName("我是短信验证");
		$req->setSmsParam("");
		$req->setRecNum($phone);
		$req->setSmsTemplateCode("SMS_001");
		$resp = $c->execute($req, $sessionKey);
		dump($resp);die;
	}
	  
	  
	 //发送短信  云短信平台
	
	function sendSMS($uid,$pwd,$mobile,$content,$time='',$mid='')
	{
		$http = 'http://http.yunsms.cn/tx/';
		$data = array
			(
			'uid'=>$uid,					//数字用户名
			'pwd'=>strtolower(md5($pwd)),	//MD5位32密码
			'mobile'=>$mobile,				//号码
			//'content'=>$content,			//内容 如果对方是utf-8编码，则需转码iconv('gbk','utf-8',$content); 如果是gbk则无需转码
			'content'=>iconv('utf-8','gbk',$content),			//内容 如果对方是utf-8编码，则需转码iconv('gbk','utf-8',$content); 如果是gbk则无需转码
			'time'=>$time,		//定时发送
			'mid'=>$mid						//子扩展号
			);
			
		$re= postSMS($http,$data);			//POST方式提交
		
		 
		if( trim($re) == '100' )
		{
			return "发送成功!";
		}
		else 
		{
			return "发送失败! 状态：".$re;
		}
	}
	
	function postSMS($url,$data='')
	{
		$post='';
		$row = parse_url($url);
		$host = $row['host'];
		$port = $row['port'] ? $row['port']:80;
		$file = $row['path'];
		while (list($k,$v) = each($data)) 
		{
			$post .= rawurlencode($k)."=".rawurlencode($v)."&";	//转URL标准码
		}
		$post = substr( $post , 0 , -1 );
		$len = strlen($post);
		
		//$fp = @fsockopen( $host ,$port, $errno, $errstr, 10);
		 
		$fp = stream_socket_client("tcp://".$host.":".$port, $errno, $errstr, 10);
		
		
		
		
		if (!$fp) {
			return "$errstr ($errno)\n";
		} else {
			$receive = '';
			$out = "POST $file HTTP/1.0\r\n";
			$out .= "Host: $host\r\n";
			$out .= "Content-type: application/x-www-form-urlencoded\r\n";
			$out .= "Connection: Close\r\n";
			$out .= "Content-Length: $len\r\n\r\n";
			$out .= $post;		
			fwrite($fp, $out);
			while (!feof($fp)) {
				$receive .= fgets($fp, 128);
			}
			fclose($fp);
			$receive = explode("\r\n\r\n",$receive);
			unset($receive[0]);
			return implode("",$receive);
		}
	}
	  
?>